package com.serverlite.framework.dao.core;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.serverlite.framework.dao.C3P0;

public class MetaData {

    public static List<String> getTables(){
        List<String> list = new ArrayList<String>();
        Connection con = C3P0.getInstance().getConnection();
        try {
            DatabaseMetaData metaData = con.getMetaData();
            ResultSet rs = metaData.getTables(null, null, null, new String[]{"TABLE"});
            while(rs.next()){
                String tableName = rs.getString("TABLE_NAME");
                if(tableName != null){
                    list.add(tableName);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public static List<Map<String,Object>> getColumns(String tableName){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        Connection con = C3P0.getInstance().getConnection();
        try {
            DatabaseMetaData metaData = con.getMetaData();
            ResultSet rs = metaData.getColumns(null, null, tableName, null);
            while(rs.next()){
              Map<String,Object> map = new HashMap<String,Object>();
              String columnName = rs.getString("COLUMN_NAME");
              String dataType  = rs.getString("DATA_TYPE");
              String typeName = rs.getString("TYPE_NAME");
              map.put("name", columnName);
              map.put("type", typeName);
              map.put("length", dataType);
              list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    
    public static Map<String,Object> columnNameMap(String tableName){
        Map<String,Object> map = new HashMap<String,Object>();
        List<Map<String,Object>> list = getColumns(tableName);
        for(Map<String,Object> c : list){
            map.put(c.get("name").toString(), tableName);
        }
        return map;
    }
}
